/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.dess.mybatis.plugins.parser;

import cn.hutool.core.util.ReflectUtil;
import com.znlh.demo.mybatisdemo.bean.Sample;
import com.znlh.demo.mybatisdemo.invoke.LocalField;

/**
 * @project-name:mybatis-demo
 * @package-name:com.znlh.demo.mybatisdemo.parser
 * @author:LiBo/Alex
 * @create-date:2020-06-16 15:52
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
public class LocalFieldParser {

    private static final String DEFAULT_PRE_FIX_TOKEN_FIELD = "@[";

    private static final String DEFAULT_POST_FIX_TOKEN = "]";

    private static final String DEFAULT_METHOD_NAME_TOKEN_L = "(";

    private static final String DEFAULT_METHOD_NAME_TOKEN_R = ")";

    private static final String DEFAULT_METHOD_PARAM_TOKEN_SPLIT = ",";

    private static final String DEFAULT_METHOD_PARAM_VALUE = "root";

    /**
     * 操作解析服务处理控制类
     *
     * @param parseStr
     * @return
     */
    public static LocalField parse(String parseStr) {
        if (parseStr.startsWith(DEFAULT_PRE_FIX_TOKEN_FIELD) && parseStr.endsWith(DEFAULT_POST_FIX_TOKEN)) {
            int startIndx = parseStr.indexOf(DEFAULT_PRE_FIX_TOKEN_FIELD) + 2;
            int endIndx = parseStr.indexOf(DEFAULT_POST_FIX_TOKEN);
            return new LocalField(parseStr.substring(startIndx, endIndx));
        }
        return null;
    }

    /**
     * 调研操作处理
     * @param localField
     * @param contextObject
     * @return
     * @throws ClassNotFoundException
     */
    public static Object invoke(LocalField localField, Object contextObject) throws ClassNotFoundException {
        // 执行调研本地方法操作
        return ReflectUtil.getFieldValue(contextObject,localField.getValue().replace("root.",""));
    }

    public static void main(String[] args){
        try {
            // userCode = @[root.key]

            System.out.println(LocalFieldParser.invoke(LocalFieldParser.parse("@[root.key]"),new Sample("1","2")));
            System.out.println(invoke(parse("@[root.key]"),new Sample("1","2")));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
